<template>
    <div class="promotion">
        <div class="cont clearfix">
          <div class="cont-left" :class="{'bigWidth': data.length=== 0}">
            <div class="items">
              <h3 class="state-title" @click="choiceAll" style="cursor: pointer"><span class="choice" :class="{'choiced' : checkArr.indexOf('0') == -1 && data.length > 0}"></span>Your Cart</h3>
              <ul class="list-box">
                <li class="li clearfix" v-for="(item,index) in data" :key="index" v-show="item.product">
                  <div class="choice-box" @click="choice(item,index)">
                    <span class="choice" :class="{'choiced': checkArr[index] == 1 ,'ss' : item.quantity < 1}" ></span>
                  </div>
                  <router-link class="img-box" target="_blank" :to="'/home/' + item.product.urlKeyWords+ '/'+ item.product.sku">
                    <img v-lazy="imgUrl+ item.product.images[0].src +'?x-oss-process=image/resize,h_150,limit_0'" ref="imgs" alt="Shop Meet50off" class="img">
                  </router-link>
                  <div class="goods-info">
                    <router-link class="h4" target="_blank" :title="item.product.headLine" :to="'/home/' + item.product.urlKeyWords+ '/'+ item.product.sku">{{item.product.headLine}}</router-link>
                    <p class="goods-type">{{productAttributes(item)}}</p>
                    <div class="num-box">
                      <span>Qty:</span>
                      <div class="num">
                        <span class="round" :class="{'noBtn' : data[index].quantity == 1}" @click="reduceNum(item,index)">
                          <i class="reduce" v-if="item.quantity !== 0"></i>
                        </span>
                        <span>{{item.quantity}}</span>
                        <span class="round" :class="{'noBtn' : data[index].quantity == data[index].currentStockQty}" @click="addNum(item,index)">
                        <i class="add">+</i>
                      </span>
                      </div>
                    </div>
                  </div>
                  <div class="price-show">
                    <p class="price1">${{item.newestPrice.amount}}</p>
                    <p class="price2"><span class="old-price">${{item.newestOriginalPrice.amount}}</span> <span class="rebate-price">You Save ${{item.newestDiscount.amount}}</span></p>
                    <p class="remove"><span class="move-wishlist" @click="moveToWishlist(item,index)">Move to Wishlist</span><span @click="removeItem(item, index,item.newestPrice.amount)">Remove</span></p>
                  </div>
                </li>
                <li class="loading-container" v-show="Loading">
                  <loading></loading>
                </li>
                <li v-show="!Loading && !data.length" class="no-result-wrapper" ref="noDataEl">
                  <no-data-show :footBtn="'Continue Shopping'"></no-data-show>
                </li>
              </ul>
            </div>
          </div>
          <!---->
          <div class="cont-right" v-if="data.length">
            <div class="back" @click="goShopping">Continue Shopping ></div>
            <div class="sumary" id="box" :style="'top:' + scrollTop + 'px'">
              <h3 class="state-title"  style="padding-left:15px">Cart Sumary</h3>
              <div class="info">
                <p class="p1 clearfix">
                  <span class="left">Subtotal({{data.length}} items)</span>
                  <span class="right">${{allTotalMoney | toFixed}}</span>
                </p>
                <p class="p1 clearfix">
                  <span class="left">Shipping & Handling</span>
                  <span class="right color-font">Free</span>
                </p>
              </div>
              <div class="info2">
                <div class="total">
                  <span class="left bold">Order Total:</span>
                  <span class="right bold">${{allTotalMoney | toFixed}}</span>
                  <span class="saveMoney">You Save ${{allSaveMoney | toFixed}}</span>
                </div>
                <div class="jinggao" v-show="noChoose" style="color:red;" ><img src="../../../static/img/jinggao.png"/>Please choose a product</div>
                <button class="btn" @click="creatOrder">Proceed To Checkout</button>
              </div>
            </div>
          </div>
      </div>
      <!--wishlist-->
        <div class="wishlist" v-show="!Loading && wishLishData.length">
          <h2 class="title2">Recent items in your wishlist</h2>
          <div class="items">
            <h3 class="state-title">Your  Wishlist</h3>
            <ul class="list-box">
              <li class="li clearfix" v-for="(item,index) in wishLishData" :key="index">
                <!--<div class="choice-box" @click="choice(item,index)">-->
                  <!--<span class="choice" :class="{'choiced': checkArr[index] == 1 ,'ss' : item.quantity < 1}" ></span>-->
                <!--</div>-->
                <router-link class="img-box" target="_blank" :to="'/home/' + item.urlKeyWords+ '/'+ item.sku">
                  <img v-lazy="imgUrl+ item.images[0].src +'?x-oss-process=image/resize,h_150,limit_0'" ref="imgs" alt="Shop Meet50off" class="img">
                </router-link>
                <div class="goods-info">
                  <router-link class="h4" target="_blank" :title="item.headLine" :to="'/home/' + item.urlKeyWords+ '/'+ item.sku">{{item.headLine}}</router-link>
                  <p class="goods-type">{{productAttributes1(item)}}</p>
                  <div class="num-box">
                    <div class="w-add-cart" @click="_addToCart(item,index)">
                      Add to Cart
                    </div>
                  </div>
                </div>
                <div class="price-show">
                  <p class="price1">${{item.price.amount}}</p>
                  <p class="price2"><span class="old-price">${{item.originalPrice.amount}}</span> <span class="rebate-price">You Save ${{item.discount.amount}}</span></p>
                </div>
              </li>
            </ul>
          </div>
        </div>
    </div>
</template>

<script>
  import NoDataShow from "base/no-data-show/no-data-show";
  import Loading from 'base/loading/loading'
  import {mapActions} from 'vuex'
  import {addToCart, getCartList, removeCartItem, checkStock, creatOrder} from 'api/cart'
  import {getWishList, addWishList, removeWishList } from 'api/my-wishlist'
  import monitoring from '../../common/js/monitoring';
  import store from '@/store'
  export default {
    data(){
      return{
        imgUrl :imgUrl ,
        data: [],
        wishLishData: [],
        Loading: true,
        noData: false,
        scrollTop: '0',     //右侧悬浮区域top值
        num: 0,   //用来判断 用户狂点 减号 限制
        checkArr: [],
        noChoose:false,
        money:"",    //facebook像素用参数 勿删
      }
    },
    created() {
      monitoring.openPromotionCart();//todo Facebook Pixel & Google Analytic Code    openPromotionCart
      this.$nextTick(() => {
        this._getCartList()
        this._getWishList()
      })

    },
    mounted(){
      window.addEventListener('scroll', this.handleScroll);  //监听滚动高度
    },
    methods:{
      goDetail(item){

      },
      goShopping(){
        this.$router.push({
          path:'/home'
        })
      },
      handleScroll () {  //实时设置top值
        var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
        if (scrollTop < $('.items')[0].offsetTop) {
          this.scrollTop = 0
        } else if (scrollTop >= $('.items')[0].offsetTop && scrollTop < $('.items')[0].offsetTop + $('.items')[0].offsetHeight) {
          this.scrollTop = scrollTop - $('.items')[0].offsetTop
        } else if (scrollTop >= $('.items')[0].offsetTop + $('.items')[0].offsetHeight) {
          this.scrollTop = $('.items')[0].offsetTop + $('.items')[0].offsetHeight
        }
      },
      _getCartList() {
        this.noData = false
        this.Loading = true
        getCartList().then(res => {
          this.data = res.cartItems
          this.Loading = false
          for(let i of this.data){     //确定勾选状态数组长度 且每个元素置为0 默认不勾选状态
            if(i.product.quantity < 1){
              this.checkArr.push("ss")
            }else{
              this.checkArr.push("1")    //默认选中状态  之前为0 不勾选状态
            }
          }
          this.totalNum = this.data.length;    //商品数量（不计单品数量）
        })
      },
      _getWishList() {
        if (store.getters.token) {// 判断是否登录
          getWishList().then(res => {
            this.wishLishData = res.wishListItems
          })
        }else {
          return false
        }
      },
      choiceAll(){
        if(this.checkArr.indexOf("0") == -1){     //全选状态
          this.checkArr = this.checkArr.map((item)=>{    //取消全选  每一项都去掉勾选
            if(item != 'ss') {
              return '0'
            }else{
              return 'ss'
            }
          });
          return false;
        }
        this.checkArr = this.checkArr.map((item)=>{    //全选
          if(item != 'ss') {
            return '1'
          }else{
            return 'ss'
          }
        });
        this.noChoose = false;
      },
      choice(item,index){
        if(item.quantity < 1) return false;   //失效商品
        if(this.checkArr[index] == 1){    //当前选中状态
          this.checkArr.splice(index,1,'0');    //点击则去掉选中状态
        }else{     //当前未选中状态
          this.checkArr.splice(index,1,'1');    //点击则选中
          this.noChoose = false;
        }
      },
      productAttributes(item) {
        let str = ''
        if (item.product.variation) {
          item.product.variation.productAttributes.forEach(function(t) {
            str += t.value + '/'
          })
        }
        return str.replace(/\/$/, '')
      },
      productAttributes1(item) {
        let str = ''
        if (item.variation) {
          item.variation.productAttributes.forEach(function(t) {
            str += t.value + '/'
          })
        }
        return str.replace(/\/$/, '')
      },
      removeOrder: function(item, index){
        let sku = ''
        if (item.product.variation) {
          sku = item.product.variation.sku
        } else {
          sku = item.product.sku
        }
        this.BtnLoading((timer, commit) => {
          removeCartItem(sku).then(res => {
            clearInterval(timer)
            commit('SET_ROUTE_LOADING', false)
            this.data.splice(index,1)
          }).catch(err => {
            clearInterval(timer)
            commit('SET_ROUTE_LOADING', false)
          })
        })
      },
      reduceNum(item,index){
        let sku = ''
        if (item.product.variation) {
          sku = item.product.variation.sku
        } else {
          sku = item.product.sku
        }
        if(this.num) return
        this.num = 1
        if(item.quantity === 1){
          this.num = 0
          return
        }
        this.BtnLoading((timer, commit) => {
          addToCart(sku, -1).then((res) => {
            this.num = 0;
            clearInterval(timer)
            commit('SET_ROUTE_LOADING', false)
            item.quantity--
            this.data[index].quantity = item.quantity
          }).catch(err => {
            this.num = 0
            clearInterval(timer)
            commit('SET_ROUTE_LOADING', false)
          })
        })

      },
      addNum(item,index){
        let sku = ''
        if (item.product.variation) {
          sku = item.product.variation.sku
        } else {
          sku = item.product.sku
        }
        if(this.num) return
        this.num = 1
        if(item.quantity === item.currentStockQty){
          this.num = 0
          return
        }
        this.BtnLoading((timer, commit) => {
          addToCart(sku, 1).then((res) => {
            clearInterval(timer)
            commit('SET_ROUTE_LOADING', false)
            this.num = 0
            item.quantity++
            this.data[index].quantity = item.quantity
          }).catch(err => {
            this.num = 0
            clearInterval(timer)
            commit('SET_ROUTE_LOADING', false)
          })
        })
      },
      removeItem(item, index,amount) {
        let sku = ''
        if (item.product.variation) {
          sku = item.product.variation.sku
        } else {
          sku = item.product.sku
        }
        removeCartItem(sku).then(res => {

          let params = {
            sku,
            amount,
          };
          monitoring.removeCart(params);//todo Facebook Pixel & Google Analytic Code    removeCart

          const total = this.data.length;
          this.data.splice(index,1)
          $('#myCartTotal').text(total - 1);
        }).catch(err => {
          console.log(err)
        })
      },
      creatOrder(){    //creat order
        console.log(this.checkArr)
        if(this.checkArr.indexOf('1') == -1) {//没有勾选任何一个地时候
          this.noChoose = true;
          return;
        }
        if(this.num) return;
        this.num = 1;
        let [dataArr,params] = [[],{}];   //组装数据发给后台
        for(let i in this.checkArr){
          if(this.checkArr[i] == 1){
            let sku = ''
            if (this.data[i].product.variation) {
              sku = this.data[i].product.variation.sku
            } else {
              sku = this.data[i].product.sku
            }
            dataArr.push({ 'sku': sku, 'qty':this.data[i].quantity })
          }
        }
        params = {
          "address": { "street1": "", "street2": "", "street3": "", "city": "", "province": "", "country": "", "postcode": "" },
          "recipient": { "contactName": "", "tel": "", "email": "" },
          "orderProducts":dataArr
        };
        this.BtnLoading((timer, commit) => {
          creatOrder(params).then((res) => {
            sessionStorage['promotionOrderNo'] = res.orderNo;    //缓存存一份订单号

            let params = {
              orderNo :res.orderNo,
              userId:res.userId,
              amount:this.money.toFixed(2)
            };
            monitoring.creatOrder(params);//todo Facebook Pixel & Google Analytic Code    creatOrder

            setTimeout(()=>{   //todo Google Analytic 确保监控请求发送出去 延迟页面跳转
              this.$router.push({name:'promotionItem',params:{orderNo:res.orderNo}});   //路由再带一份订单号  双重保证
            },250)

            clearInterval(timer)
            commit('SET_ROUTE_LOADING', false);
            this.num = 0;
          }).catch(err => {
            this.num = 0;
            clearInterval(timer)
            commit('SET_ROUTE_LOADING', false);
          })
        })

      },
      moveToWishlist(item,index){
        let sku = ''
        if (item.product.variation) {
          sku = item.product.variation.sku
        } else {
          sku = item.product.sku
        }
        addWishList(sku).then(res => {
          monitoring.addWishList({"sku" : sku});//todo Facebook Pixel & Google Analytic Code    addWishList
          this.data.splice(index,1)
          this._getWishList()
        }).catch(err => {
          console.log(err)
        })
      },
      _addToCart(item,index){
        let sku = ''
        if (item.variation) {
          sku = item.variation.sku
        } else {
          sku = item.sku
        }
        removeWishList(sku).then((res) => {
          this.wishLishData.splice(index,1)
        })
        addToCart(sku,1).then((res) => {
          monitoring.addCart({"sku" : sku});//todo Facebook Pixel & Google Analytic Code    addCart
          this._getCartList()
        }).catch(err => {

        })

      },
      ...mapActions([
        'StartLoading',
        'BtnLoading'
      ])
    },
    computed :{
      allTotalMoney : function(){
        let money =0;
        this.data.forEach((item,index)=>{
          if(this.checkArr[index] == 1 && item.quantity >= 1){
            money += item.newestPrice.amount * item.quantity
          }
        });
        this.money = money;   //facebook像素用参数 勿删
        return money

      },
      allSaveMoney : function(){
        let saveMoney =0 ;
        this.data.forEach((item,index)=>{
          if(this.checkArr[index] == 1 && item.quantity >= 1){
            saveMoney += item.newestDiscount.amount * item.quantity
          }
        });
        return saveMoney
      }
    },
    destroyed() {
      window.removeEventListener('scroll', this.handleScroll);  //解绑事件
    },
    filters: {
      toFixed(value) {
        return value.toFixed(2)
      }
    },
    components:{
      NoDataShow,
      Loading,
    },
    watch: {
      '$route'(to, from) {
        console.log(to)
      }
    }
  }

</script>

<style scoped lang="stylus" rel="stylesheet/stylus">

  .choice
    border:1px solid #ddd
    width:15px
    height:15px
    display:inline-block
    border-radius:50%
    position:absolute
    left: 8px
    top: 50%;
    margin-top: -7px;
    cursor: pointer
  .choiced
    background url(true.png) no-repeat center center
    border:none
  .ss
    background #ddd!important
  .no-result-wrapper
    width: 100%
    height:100%
    border-bottom: 1px solid #dcdcdc;
  .loading-container
    width: 100%
    height: 276px;
    padding-top: 192px;
    border-bottom: 1px solid #dcdcdc;
  .state-title
    text-align left
    height:44px
    line-height:44px
    padding-left: 34px;
    position: relative
    font-size:18px
    color: #333
    background #f6f7f8
    border-bottom:1px solid #dcdcdc
  .down
    transition: all 0.4s;
  .Upward
    transform:rotate(-180deg);
    transition: all 0.4s;
  .mobile-scroll
    &::-webkit-scrollbar /*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
      width: 6px;
      height: 6px;
      background-color: #F5F5F5;
    &::-webkit-scrollbar-track  /*定义滚动条轨道 内阴影+圆角*/
      -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
      border-radius: 10px;
      background-color: #FFF;
    &::-webkit-scrollbar-thumb /*定义滑块 内阴影+圆角*/
      border-radius: 10px;
      -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
      background-color: #efefef;
  .variation-trait
    display: inline-block;
    width: 100%
    background-color: #fff
    border: 1px solid #a5a8ab
    border-radius: 2px
    font-size: 17px
    transition: background-color .25s ease-out,border-color .25s ease-out,color .25s ease-out
    background: no-repeat 100%
    background-image: url(../../../static/img/arrow-green.svg);
    background-size: 40px 20px
    padding: 8px 36px 8px 12px
    appearance: none
    outline none
  .select-box
    display:none
    width:100%;
    height:auto
    position:absolute
    left:-1px
    top:40px;
    overflow auto
    background:#fff
    border:1px solid #ddd
    text-align center
    z-index: 1;
    .select-li
      height:36px;
      line-height:36px;
      font-size:14px;
      cursor:pointer
      &:hover
        background #efefef
      &:last-child
        border-bottom:none
  .left
    float:left
  .right
    float:right
  .promotion
    width:100%
    .cont
      margin-top:30px;
      width:100%
      height:auto;
      .cont-left
        height:100%
        width:716px;
        float:left;
      .bigWidth
        width:100%
      .cont-right
        width: 330px;
        float:right
        position:relative
        .sumary
          border:1px solid #dcdcdc
          height:auto
          position: absolute;
          left: 0;
          width: 100%;
          .info
            border-bottom 1px solid #dcdcdc
            padding:10px 15px;
            color:#707070
            .p1
              line-height:40px;
              .color-font
                color:#4999e2
          .info2
            padding:18px 15px;
            .total
              font-size:23px;
              line-height: 30px;
              margin-bottom: 15px;
              display flex
              justify-content space-between
              position:relative
              margin-bottom 20px
              .saveMoney
                position:absolute
                right:2px
                bottom: -21px;
                font-size: 14px;
                line-height: 20px
                color:#18823a

            .jinggao
              width 100%
              display flex
              justify-content center
              align-items center
              font-size:15px;
              margin-bottom 5px
              img
                height 16px
                margin-right 5px
            .btn
              width: 100%
              height:40px
              line-height:40px
              border:none
              border-radius:2px
              background #18823a
              color: #ffffff
              font-size:16px
              cursor:pointer
              /*margin:30px 0 0px*/
        .back
          position: absolute
          right:0
          top:-40px
          float:right
          color #18823a
          font-size:14px
          cursor:pointer
  .items
    border:1px solid #dcdcdc
    border-bottom:none
    .li
      padding: 15px 20px 12px 26px
      border-bottom:1px solid #dcdcdc
      font-size: 18px
      display:flex
      position: relative
      .img-box
        width: 200px
        height: 135px;
        cursor: pointer
        padding-right:20px
        background #fff
        text-align center
        .img
          max-width:200px
          max-height:135px
          vertical-align: middle
      .choice-box
        cursor: pointer
        position: absolute
        height: calc(100% - 20px)
        width: 26px
        left: 0
      .choice
        position:absolute
        left: 50%
        margin-left: -5px
        top: 44%
      .goods-info
        color:#333
        flex 1
        position:relative
        .h4
          width: 100%
          line-height: 22px
          cursor: pointer
          font-size: 16px
          text-overflow: -o-ellipsis-lastline;
          text-overflow: ellipsis;
          overflow: hidden;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          color:#474747
          &:hover
            text-decoration: underline
        .goods-type
          font-size 14px
          color:#bbb
          margin-top: 10px
          height: 14px
        .num-box
          margin-top:25px
          font-size:18px
          display flex
          align-items center
          color: #000
          span
            vertical-align middle
          .num
            margin-left: 15px
            height:40px
            line-height:40px
            position:relative
            cursor:pointer
            display flex
            align-items center
            .round
              display:inline-block
              width:24px
              height:24px
              border:1px solid #ddd
              border-radius:50%
              position:relative
              margin:0 6px
            .reduce
              background:#18823a
              position:absolute
              left: 6px
              top: 11px
              display: inline-block
              width: 12px
              height: 2px
              font-style:normal
            .add
              color: #18823a
              font-size: 27px
              position: absolute
              left: 4px
              top: -8px
              font-style:normal
            .noBtn>.reduce
              background #ddd
            .noBtn>i.add
              color #ddd
          .w-add-cart
            display: inline-block
            width: 119px
            height: 34px
            line-height: 34px
            border: solid 1px #18823a;
            font-size: 14px;
            cursor: pointer
            text-align center
            color: #18823a
      .price-show
        width:190px
        text-align right
        color:#333
        .price1
          font-size:24px
          line-height:50px
        .remove
          color:#18823a
          font-size:14px
          margin-top:39px
          cursor:pointer
          span
            vertical-align middle
          .move-wishlist
            display:inline-block
            height: 15px
            line-height: 15px
            padding-right: 15px
            border-right: 1px solid #cacaca
            margin-right:15px
        .price2
          margin-top: -6px;
          padding-right: 2px;
          .old-price
            margin-right:5px;
            text-decoration:line-through
            color:#98999a
          .rebate-price
            color:#4999e2
            font-size: 14px;

  .wishlist
    width:716px
    .title2
      font-size: 24px
      color:#333
      margin-top:40px
      margin-bottom:20px

</style>
